package main.java;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import model.entities.MeasureUnit;
import model.entities.UserCode;

public class DAO {

	private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("gsi"); 

	public DAO()
	{
	}

	public void addUserCode(UserCode uc) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction entityTransaction = entityManager.getTransaction();

		entityTransaction.begin();

		entityManager.persist(uc);

		entityTransaction.commit();
		entityManager.close();
	}

	public List<MeasureUnit> getMeasureUnits() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction entityTransaction = entityManager.getTransaction();

		entityTransaction.begin();

		Query allMeasureUnitsQuery = entityManager.createQuery("FROM MeasureUnit");
		@SuppressWarnings("unchecked")
		List<MeasureUnit> allMeasureUnits = allMeasureUnitsQuery.getResultList();

		entityTransaction.commit();
		entityManager.close();

		return allMeasureUnits;
	}

	public MeasureUnit getMeasureUnitById(Long id)
	{
		List<MeasureUnit> units = getMeasureUnits();
		for(MeasureUnit unit : units)
		{
			if(unit.getId().longValue() == id.longValue())
			{
				return unit;
			}
		}
		return null;
	}

	public List<UserCode> getUserCodes() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction entityTransaction = entityManager.getTransaction();

		entityTransaction.begin();

		Query allUserCodesQuery = entityManager.createQuery("FROM UserCode");
		@SuppressWarnings("unchecked")
		List<UserCode> allUserCodes = allUserCodesQuery.getResultList();

		entityTransaction.commit();
		entityManager.close();

		return allUserCodes;
	}

	public List<UserCode> getUserCodesByCode(String code)
	{
		List<UserCode> returnList = new ArrayList<UserCode>();
		List<UserCode> userCodes = getUserCodes();
		for(UserCode userCode : userCodes)
		{
			if(userCode.getCode().intValue() == Integer.parseInt(code))
			{
				returnList.add(userCode);
			}
		}
		return returnList;
	}
}
